package creative.fire.interview.redhat;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 
 * @author luh
 * 2012.5.3
 */
public class ProxyTest {
	public static void main(String[] args) {
		HelloWorld hw = new HelloWorldImpl();
		InvocationHandler handler = new HelloWorldHandler(hw);
		ClassLoader loader = hw.getClass().getClassLoader();
		Class<?>[] interfaces = hw.getClass().getInterfaces();
		HelloWorld proxy = (HelloWorld) HelloWorldProxy.newProxyInstance(loader, interfaces, handler);
		proxy.sayHelloWorld("eric");
	}

	interface HelloWorld {
		void sayHelloWorld(String name);
	}

	static class HelloWorldImpl implements HelloWorld {
		public void sayHelloWorld(String name) {
			System.out.println("Hello World! "+name);
		}
	}

	static class HelloWorldProxy extends Proxy {
		private static final long serialVersionUID = -5893759766129715077L;

		protected HelloWorldProxy(InvocationHandler h) {
			super(h);
		}
	}

	static class HelloWorldHandler implements InvocationHandler {
		//要代理的原始对象 
		private Object objOriginal;

		public HelloWorldHandler(Object obj) {
			this.objOriginal = obj;
		}

		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			Object result;
			//方法调用之前 
			doBefore();
			//调用原始对象的方法 
			result = method.invoke(this.objOriginal, args);
			//方法调用之后 
			doAfter();
			return result;
		}

		private void doBefore() {
			System.out.println("before method invoke!");
		}

		private void doAfter() {
			System.out.println("after method invoke!");
		}
	}
}
